package db

import (
	"database/sql"
	_ "mysql"
)

func Query(sqlstr string) (rows []interface{}, e error) {
	db, err := sql.Open("mysql", "root:toor@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return nil, err
	}
	defer db.Close()
	r, err := db.Query(sqlstr)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	columns, err := r.Columns()
	if err != nil {
		return nil, err
	}
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	for r.Next() {
		err := r.Scan(scanArgs...)
		if err != nil {
			return nil, err
		}
		row := make(map[string]interface{})
		for i, col := range values {
			if col != nil {
				row[columns[i]] = string(col.([]byte))
			}
		}
		rows = append(rows, row)
	}
	return rows, nil
}
func Insert(sqlstr string, values []interface{}) error {
	db, err := sql.Open("mysql", "root:toor@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return err
	}
	defer db.Close()
	stmt, err := db.Prepare(sqlstr)
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(values...)
	if err != nil {
		return err
	}
	_, errI := res.LastInsertId()
	if errI != nil {
		return errI
	}
	return nil
}
func Delete(sqlstr string, values []interface{}) error {
	db, err := sql.Open("mysql", "root:toor@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return err
	}
	defer db.Close()
	stmt, err := db.Prepare(sqlstr)
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(values...)
	if err != nil {
		return err
	}
	_, errD := res.RowsAffected()
	if errD != nil {
		return errD
	}
	return nil
}
func Update(sqlstr string, values []interface{}) error {
	db, err := sql.Open("mysql", "root:toor@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return err
	}
	defer db.Close()
	stmt, err := db.Prepare(sqlstr)
	if err != nil {
		return err
	}
	defer stmt.Close()
	res, err := stmt.Exec(values...)
	if err != nil {
		return err
	}
	_, errU := res.RowsAffected()
	if errU != nil {
		return errU
	}
	return nil
}
